package chaincode

import (
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"github.com/hyperledger/fabric/core/chaincode/shim"
	"github.com/hyperledger/fabric/protos/msp"

	"github.com/golang/protobuf/proto"

	"encoding/json"
)

type TisaneRecord struct {
	HisHospital   string `json:"his_hospital"`  //医疗机构名称
	HospitalCode  string `json:"hospital_code"` //医疗机构代码
	RecipeCode    string `json:"recipe_code"`   //医院处方号
	Name          string `json:"name"`          //患者姓名
	AdjustStart   string `json:"adjust_start"`
	AdjustEnd     string `json:"adjust_end"`
	ReviewStart   string `json:"review_start"`
	ReviewEnd     string `json:"review_end"`
	BubbleStart   string `json:"bubble_start"`
	BubbleEnd     string `json:"bubble_end"`
	TisaneStart   string `json:"tisane_start"`
	TisaneEnd     string `json:"tisane_end"`
	PackStart     string `json:"pack_start"`
	PackEnd       string `json:"pack_end"`
	DeliveryStart string `json:"delivery_start"`
	DeliveryEnd   string `json:"delivery_end"`
}
type VaildQueryParam struct {
	RecipeCode   string `json:"recipe_code"`
	HospitalCode string `json:"hospital_code"`
	Name         string `json:"name"`
}

func GenerateRecordKey(HospitalCode string, RecipeCodeName string) string {
	uniKey := fmt.Sprintf("%d.%s", HospitalCode, RecipeCodeName)
	sha256bytes := sha256.Sum256([]byte(uniKey))
	return hex.EncodeToString(sha256bytes[:])
}
func getTraderMspID(stub shim.ChaincodeStubInterface) (string, error) {
	creatorCert, err := stub.GetCreator() //获取谁做的交易　获取交易者的证书
	if err != nil {
		return "", NewErrInfo(ERR_GET_TRADER, err)
	}

	identity := msp.SerializedIdentity{}
	err = proto.Unmarshal(creatorCert, &identity)
	if err != nil {
		return "", NewErrInfo(ERR_UNMARSHAL, err)
	}
	return identity.Mspid, nil
}

type EventMessage struct {
	From    string `json:"from"`
	EvType  string `json:"evtype"`
	Payload []byte `json:"payload"`
}

func NewEventMessage(from string, eType string, evData []byte) *EventMessage {
	return &EventMessage{
		From:    from,
		EvType:  eType,
		Payload: evData,
	}
}

func (e *EventMessage) Marshal() ([]byte, error) {
	bs, err := json.Marshal(e)
	if err != nil {
		return nil, NewErrInfo(ERR_MARSHAL, err)
	}
	return bs, nil
}

func (e *EventMessage) Unmarshal(data []byte) error {
	err := json.Unmarshal(data, e)
	if err != nil {
		return NewErrInfo(ERR_UNMARSHAL, err)
	}
	return nil
}
